﻿/***************************** Ccay IGrid Individuation *************************************/
(function(IGrid) {
	var customMsg = IGrid.Const.I18n.custom = {
		dialogTitle : "ccay.common.igrid.customSetting",
		customTitle : "ccay.common.igrid.optionSetting",
		columnsName : "ccay.common.igrid.columnSetting",
		columnsDesc : "ccay.common.igrid.columnDesc",
		colHeader : "ccay.common.igrid.columnName",
		colWidth : "ccay.common.igrid.width",
		colFreeze : "ccay.common.igrid.freeze",
		colHidden : "ccay.common.igrid.hidden",
		notHiddenMsg : "ccay.common.message.notHiddenAll",
		notFreezeMsg : "ccay.common.message.notFreezeAll",
		btnDefault : "ccay.common.button.defalutConfig",
		msgDefault : "ccay.common.igrid.defalutConfigMsg",
		changeDataMsg : "ccay.common.igrid.changeDataMsg"
	};

	var individuation = IGrid.Individuation = {
		/** @description 设置个性化编辑器的属性
		 *  @param {Object} grid IGrid对象
		 *  @param {Object} op grid的配置信息
		 */
		setCustomProp : function(grid, op) {
			// 重新初始化时，不执行
			if (!op._reIniting) {
				var customLayout = Ccay.ViewLayout.create({
						layout :'<tr deep="${item.ePropDeep}"><td style="padding-left:${item.ePropPadding}px" class="ccay-igridprop-name ${item.titleMark}"><span>${item.ePropName}</span></td><td class="ccay-prop-input"><div class="igrid-individuation-editor">${item}</div>${item.ePropDesc}</td></tr>',
						setItemOp:function(item){
							item = this.base.setItemOp.call(this,item);
							
							var bool = false;
							for(var i = 0,curCol = op.columns[0] ; curCol ; i++ , curCol = op.columns[i] ){
								if (curCol.rule && curCol.rule.required || curCol.hiddenable === false) {
									bool = true;
									break;
								}
							}
							if (item.ePropDesc && bool) {
								item.ePropDesc = '<div class="ccay-msg msg-tip"><a class="ccay-icon warning nocursor"></a><b class="i18n" i18nKey="ccay.common.message.topBoxIcon"></b><span>' + ' ' + item.ePropDesc + '</span></div>';
							}else {
								item.ePropDesc = "";
							}
							return item;
						}
					}, "prop"),
					operateButtons = Ccay.UI.PropEditor.operateButtons,
					propOp = {
						dialogTitle : customMsg.dialogTitle,
						dialogWidth : 600,
						//title : customMsg.customTitle,
						showLoading: op.customLoading,
						getChanged: false,
						arrKeys : {columns : "field"},
						props : {},
						config : {},
						changeHandler: {},
						layout: customLayout,
						buttons : [operateButtons.save, operateButtons.reset, {
							// 图片 button liujian
							type:"imgBtn",
				      	  	icon:"confirm",
				      	  	cls:"ccay-icon",
							text : customMsg.btnDefault,
							click : function() {
								var defConfig = $("#propGrid").parents("form:first").manager().op.defConfig;
								individuation.execSaveProp(grid, null, defConfig, $(this));
							}
						}, operateButtons.cancel],
						fnSave : function(conf) {
							individuation.execSaveProp(grid, conf, this.defConfig);
						},
						fnComplete: function () {
							// 判断是否是服务器端排序
							if (!this.op.config.remoteSort) {
								// 判断是否有行渲染设置，有则隐藏
								if (op.rowRender == "group" || op.rowRender == "rowSpan") {
									this.find("[name='rowRenderOp.order']").parents("tr:first").hide().prev().hide();
								}
								var columnsEditor = this.find("[name='columns']").manager(), 
									// 获取sort列的索引
									hideColIndex = columnsEditor.getCellByField(0, "sort").attr('_col') * 1;
								// 隐藏sort列
								columnsEditor.hideColumns(hideColIndex, hideColIndex + 1);
							}
						}
					};
				// 设置默认的列配置参数
				individuation.setDefaultOp(grid, op, propOp.props, propOp);
				// 设置默认的列数据
				propOp.props.columns.ePropConf = individuation.setColData(op.columns, propOp.props.columns.editorOp.columns, grid);
				// 保存编辑器属性的初始值
				grid.dom.data("propOp", propOp);
			}
		},
		/** @description 清除列设置
		 * 	@param {Array} columns 列设置
		 */
		clearColProp: function (columns) {
			var clears = ["colsort", "freezeable", "hidden"];
			$.each(columns, function (i, col) {
				$.each(clears,function(n, name){
        			col[name] = null;
        		});
			});
		},
		/** @description 执行保存设置
		 * 	@param {Object} e 事件对象
		 * 	@param {Object} target 当前对象
		 *  @param {Object} grid IGrid对象
		 *  
		 */
		execSaveProp: function (grid, conf, defConfig, btnDefault) {
			var gridOp = grid.op, changeDatas = grid.getRecords();
			if (conf) {
				// 清除排序的设置
				individuation.clearColProp(defConfig.columns);
				var confOrder = conf.rowRenderOp && conf.rowRenderOp.order,
					changeConf = Ccay.DataHelper.getDataChange(conf, defConfig, {columns : "field"}) || {},
					changeOrder = changeConf && changeConf.rowRenderOp && changeConf.rowRenderOp.order;
				// 优先级不存在时，以列上面的排序为准
				if (confOrder && !confOrder.length) {
					changeConf.rowRenderOp = conf.rowRenderOp;
				} else {
					// 优先级存在时，清除列上面的排序
					if (changeConf.rowRenderOp) {
						changeConf.rowRenderOp = conf.rowRenderOp;
						if (changeConf.columns) {
							$.each(changeConf.columns, function (i, col) {
								col && col.sort && (col.sort = null);
							})
						}
					}
				}
				// 每次修改设置时，保存到数据库
				grid.saveCustom(changeConf);
				var changeGridOp = $.extend(true, {}, changeConf);
				// 存在变更数据，将不执行重新初始化
				if (conf.remoteSort && changeDatas) {
					Ccay.UI.showMessage(customMsg.changeDataMsg, "warn");
				} else {
					// 不存在改变数据，或者不是本地排序，则重新发送请求
					if (($.isEmptyObject(changeGridOp) || changeGridOp.remoteSort !== false) && grid.dom.data("defGridOp").remoteSort) {
						var orderArray = changeGridOp.rowRenderOp && changeGridOp.rowRenderOp.order;
						if (orderArray && orderArray.length) {
							changeGridOp._sortSetting = {isRemoteSort: true, sort: orderArray};
						} else {
							changeGridOp._sortSetting = null;
						}
						// 清除数据
						grid.clearCache();
					} else {
						changeGridOp.sort = gridOp.sort;
					}
					// 重新初始化
					grid.reInit(changeGridOp);
				}
			} else {
				Ccay.UI.confirm(customMsg.msgDefault, function(result) {
					
					if (result) {
						// 每次修改设置时，保存到数据库
						grid.saveCustom(defConfig);
						var changeGridOp = $.extend(true, {}, defConfig);
						// 存在变更数据，将不执行重新初始化
						if (gridOp.remoteSort && changeDatas) {
							Ccay.UI.showMessage(customMsg.changeDataMsg, "warn");
						} else {
							
							grid.reInit(changeGridOp);
						}
						btnDefault.parents("div.ccay-dialog:first").manager().close();
					}
				});
			}
		},
		/** @description 绑定设置图标的事件
		 * 	@param {Object} e 事件对象
		 * 	@param {Object} target 当前对象
		 *  @param {Object} grid IGrid对象
		 *  
		 */
		settingClick : function(target, grid, op) {
			var propOp = $.extend(true, {}, grid.dom.data("propOp")), 
				gridSetting = Ccay.Personalized.getCurrPageSettings(grid.id);
			// 若个性化存在，则同步，否则复制
			if (gridSetting) {
				// 同步个性化中的设置
				propOp.config = gridSetting;
				// 若是排序标识，则改变默认设置
				if (gridSetting.hasColSort) {
					var tempColSort = individuation.setColData(op.columns, propOp.props.columns.editorOp.columns, grid);
					Ccay.DataHelper.applyArrayChange(tempColSort, propOp.props.columns.ePropConf, "field");
					propOp.props.columns.ePropConf = tempColSort;
				}
			}
			// 重建弹出框的属性编辑器
			Ccay.UI.openPropEditor(propOp,op.profileOpen);
		},
		/** @description 设置默认的列设置
		 *  @param {Object} grid IGrid对象
		 *  @param {Object} op grid的配置信息
		 */
		setDefaultOp : function(grid, op, gridProps, propOp) {
			if (op.allowSort && op.remoteSort && !op.lazyLoad) {
				gridProps.remoteSort = {};
			}
			var columnsProps = gridProps.columns = {
				type : "tableEditor",
				ePropName : customMsg.columnsName,
				ePropDesc : customMsg.columnsDesc,
				ePropConf : [],
				editorOp : {
					width : 518,
					columns : [{
						field : "header",
						width : (!op.percentWidth && op.allowFreezen) ? 150 : 200,
						header : customMsg.colHeader,
						editable : false,
						content : "${#Ccay.UI.IGrid.Individuation.setRequiredStyle(data)}"
					},{
						field : "hidden",
						width : (op.allowSort && op.remoteSort) ? 80 : 100,
						header : customMsg.colHidden,
						type : "bool",
						format : {isBool: true, noFork : true},
						editorOp:{shortChecked:true},
						cssName:"center",
						editable:false,
						content:"${#Ccay.Format.boolRender('propGrid',hidden,data._noHidden)}",
						fnEndEdit : function(value, rowData, td, col, oldValue) {
							var op = this.op, dataLength = op.Storage.len();
							// 若勾选则隐藏个数加1，否则减1
							if (value) { 
								op._hideCount++; 
								// 若该列是冻结的，则冻结树减1
								rowData.freezeable && op._freezeCount--;
							} else {
								op._hideCount--;
								// 若该列是冻结的，则冻结树加1
								rowData.freezeable && op._freezeCount++;
							}
							// 若总个数等于数据集长度，则提示不能全部隐藏，该单元格修改值不变
							if (op._hideCount == dataLength) {
								Ccay.UI.showMessage(customMsg.notHiddenMsg, "warn");
								// 不改变原始值，则计算隐藏则减少一个
								op._hideCount--;
								return false;
							}
							// 若非隐藏的冻结列少于2列，则标识提示信息，该单元格修改值不变
							if (!grid.op.percentWidth && grid.op.allowFreezen && op._freezeCount && (dataLength - op._hideCount - 2) < op._freezeCount) {
								Ccay.UI.showMessage(customMsg.notFreezeMsg, "warn");
								// 不改变原始值，则计算非隐藏的冻结则减少一个
								if (!value) { 
									op._hideCount++; 
									// 若该列是冻结的，则冻结树减1
									rowData.freezeable && op._freezeCount--;
								} else {
									op._hideCount--;
									// 若该列是冻结的，则冻结树加1
									rowData.freezeable && op._freezeCount++;
								}
								return false;
							}
						}
					}],
					fnDataBindComplete : function() {
						var hideCount = 0, freezeCount = 0, op = this.op;
						// 遍历数据集
						op.Storage.filter(function(item){
							// 若该列是隐藏列，则计数加1
			        		item.hidden && hideCount++;
			        		// 若该列是冻结列，并且非隐藏列，则计数加1
			        		item.freezeable && !item.hidden && freezeCount++;
			        	});
						// 缓存隐藏列个数
						op._hideCount = hideCount;
						// 缓存非隐藏冻结列个数
						op._freezeCount = freezeCount;
					},
					fnBeforeEdit : function(value, td, col) {
						// 如果该字段是隐藏，并且该列是不能被隐藏的，则该单元格不能编辑
						if (col.field == "hidden") {
							// 获取行数据
							var rowData = this.getRowData(td);
							// 若行数据标示不是隐藏列，则返回false，不能编辑
							if (rowData._noHidden) {
								return false;
							}
						}
					}
				}
			};
			if(op.customSettingRowGroup){
				columnsProps.editorOp.rowRender = "rowSpan";
				columnsProps.editorOp.wrap = true;
				columnsProps.editorOp.columns.unshift({
					field : "rowGroupName",
					width : 120,
					header : "ccay.common.igrid.customRowGroupName",
					cssName : "customSettingRowGroup",
					editable : false,
					rowSpan:true
				});
			}
			// 百分比模式下，不进行冻结操作
			if (!op.percentWidth && op.allowFreezen) {
				columnsProps.editorOp.columns.push({
					field : "freezeable",
					width : (op.allowSort && op.remoteSort) ? 80 : 100,
					header : customMsg.colFreeze,
					type : "bool",
					format : {isBool: true, noFork : true},
					editorOp:{shortChecked:true},
					cssName:"center",
					editable:false,
					content:"${#Ccay.Format.boolRender('propGrid',freezeable)}",
					fnEndEdit : function(value, rowData, td, col, oldValue) {
						var op = this.op,
							dataLength = op.Storage.len();
						// 若该列不是隐藏列时
						if (!rowData.hidden) {
							// 勾选则隐藏个数加1，否则减1
							value ? op._freezeCount++ : op._freezeCount--;
							// 若非隐藏的冻结列少于2列，则标识提示信息，该单元格修改值不变
							if ((dataLength - op._hideCount - 2) < op._freezeCount) {
								Ccay.UI.showMessage(customMsg.notFreezeMsg, "warn");
								// 不改变原始值，则计算非隐藏的冻结则减少一个
								value ? op._freezeCount-- : op._freezeCount++;
								return false;
							}
						}
					}
				});
			}
			if (op.allowSort && op.remoteSort && (op.rowRender == "group" || op.rowRender == "rowSpan")) {
				gridProps.rowRenderOp = {};
			}
			// 执行所有插件中的个性化设置
			var gridPlugin = Ccay.UI.XControl.getPlugin(grid.type);
			gridPlugin.fireAll("individuation", grid, op, gridProps, columnsProps.editorOp.columns, propOp);
		},
		/** @description 设置编辑器props属性中grid（除列外）的属性
		 *  @param {Object} gridProps grid的默认设置
		 *  @param {Object} gridConfig grid的变化设置
		 *  @param {Object} gridOp grid的配置信息
		 */
		setGridData : function(gridProps, gridConfig, gridOp) {
			// 遍历grid的默认配置，并赋初始值
			$.each(gridProps, function(key, setting) {
				if (key !== "columns") {
					gridOp[key] && (gridConfig[key] = gridOp[key]);
				}
			});
		},
		/** @description 设置编辑器props属性中grid列的数据
		 *  @param {Object} columnsOp grid的列设置
		 *  @param {Object} columnProps grid的列的默认设置
		 *  @param {Boolean} isInit 是否是初始化
		 *  @param {Object} op grid的配置信息
		 */
		setColData : function(columnsOp, columnProps, grid) {
			var colConfs = [];
			// 循环grid的列设置
			for (var i = 0, col; col = columnsOp[i]; i++) {
				if (!col.inner && !col.columnType) {
					var colConf = {}, field;
					// 循环个性化的列设置
					for (var j = 0, colProp; colProp = columnProps[j]; j++) {
						field = col[colProp.field];
						// 初始化给每一列赋默认值
						colConf[colProp.field] = (field != null) ? field : null;
						// 如果当前列是必填项，则该列不能隐藏
						if (col.rule && col.rule.required || col.hiddenable === false) {
							colConf._noHidden = true;
						}
						colConf.header = col.header ? $i18n(col.header).encode() : col.customHeader;
						colConf.colsort = col.colsort;
						colConf.width = col.width;
						colConf.field = col.field;
						colConf.rowGroupName = col.rowGroupName || "";
					}
					colConfs.push(colConf);
				}
			}
			if(grid.op.customSettingRowGroup){
				var newColConfs = colConfs.sort(function(v1,v2){
					if(v1.rowGroupName < v2.rowGroupName){
						return -1;
					}else if(v1.rowGroupName > v2.rowGroupName){
						return 1;
					}else{
						return 0;
					}
				});
				return newColConfs;
			}
			return colConfs;
		},
		/** @description 设置必填项的样式
		 *  @param {Object} data 数据对象
		 */
		setRequiredStyle : function(data) {
			return data._noHidden ? ((data.header||data.customHeader) + "<font color='red'>&nbsp;*</font>") : (data.header||data.customHeader);
		},
		/** @description 保存列宽改变
		 *  @param {Object} grid IGrid对象
		 *  @param {Number} width 改变的列宽度
		 *  @param {Object} column 改变的列设置
		 *  @param {Object} cell 单元格对象
		 */
		saveWidthChange : function (grid, width, column, cell) {
			// 不是改变的内置列，则进行个性化保存
			if (!column.inner) {
				var newColumns= [], op = grid.op;
				// 百分比模式下，需要将所有的列宽进行保存
				if (op.columns && op.percentWidth) {
					// 遍历所有的列宽
					$.each(op.columns, function (colIndex, col) {
						if (!col.inner && !col.hidden) {
							if (col.field == column.field) {
								newColumns.push({field : col.field, width : parseFloat(width).toFixed(2) + "%"});
							}  else {
								newColumns.push({field : col.field, width : parseFloat(col._curWidth).toFixed(2) + "%"});
							}
						}
					});
				} else {
					newColumns.push({field : column.field, width : width});
				}
				grid.saveCustom({hasColResize: true,showMessage:false, columns: newColumns});
			}
		}
	};

	/** 注册个性化设置插件 */
	Ccay.UI.XControl.addPlugin("XGrid", "individuation", {
				preInit: function (grid, op) {
					// 保存默认设置
					!op._reIniting && grid.dom.data("defGridOp", $.extend(true, {}, op));
					// 个性化接口实现
					if (op.customSetting) {						
						// 设置个性化的参数
						individuation.setCustomProp(grid, op);
						// 执行个性化设置
						Ccay.Personalized && Ccay.Personalized.iGridProcessor && Ccay.Personalized.iGridProcessor(grid, op);
						// 列宽改变时，保存个性化设置
						op.handler.widthChange.add(individuation.saveWidthChange);
					}
				},
				build : function(grid, op) {
					
				},
				miniToolBar: function (grid, op, toolBarButton) {
					// 添加个性化图标按钮到工具栏中
					if (op.customSetting) {
						if(op.profileSelectPanel){
							var pageKey = Ccay.Personalized.getPageKey(),gridId=grid.id,settingKey=pageKey+"#"+gridId;
							var url = "services/ccay/personalized/setting/list/page?settingKey="+pageKey+"&gridId="+gridId;
							$(op.profileSelectPanel).dropdown({
								ajax:{
									url:url
								},
								allowDel:true,
								fnBeforeRemoveItem:function(datas,op,selector){
									var url = "services/ccay/personalized/setting/delSingle/{0}".formatValue(datas.settingId);
									Ccay.doDelete({url:url});
								},
								valueField:"profileName",
								displayField:"profileName",
								fnBeforeBinded:function(selector,datas,op){
									for(var i=0;i<datas.length;i++){
										if(datas[i].settingKey.indexOf(settingKey)==-1 || datas[i].settingKey==settingKey){
											datas.splice(i,1);
											i--;
										}else{
											datas[i].profileName = datas[i].settingKey.replace("!"+settingKey,"");
										}
									}
								},
								fnSelected:function(value, text,oldValue, item,selector,data){
									if(data && oldValue!=value){
										var conf = $.parseJSON(data.settingContent);
										var changeGridOp = $.extend(true, {}, conf);
										Ccay.Personalized.saveSetting(grid.id, changeGridOp, op.hasColResize ? null : $.noop, true);
										if(grid.getRecords()){
											Ccay.UI.showMessage(customMsg.changeDataMsg, "warn");
										}else{
											// 重新初始化
											grid.reInit(changeGridOp);
										}
									}
								}
							});
						}
						toolBarButton.push({
							type: "img",
							icon: "setting",
							text: "ccay.common.igrid.customSetting",
							click: function () {
								individuation.settingClick($(this), grid, op);
							}
						});
					}
				}
			});
			
	/** manager扩展 */
	Ccay.UI.XControl.extendIManager("XGrid", {
		/** @description 保存个性化到数据库
		 * 	@param {Object} op 变更的参数对象
		 */
		saveCustom: function (op) {
			var customSetting = Ccay.Personalized.getCurrPageSettings(this.id) || {},
				hasColSort, switchMode;
			if (!$.isEmptyObject(op)) {
				// 当列拖拽和改变列宽的时候，应用变化设置，否则覆盖
				if (op.hasColSort || op.hasColResize) {
					// 应用变化的设置
					Ccay.DataHelper.applyChangeData(customSetting, op, {columns: "field"});
				} else {
					// 若是列拖拽的个性化，则需保存列拖拽的标示
					customSetting.hasColSort && (hasColSort = true);
					customSetting.switchMode && (switchMode = customSetting.switchMode);
					// 替换原始设置
					customSetting = $.extend(true, {}, op);
					hasColSort && (customSetting.hasColSort = true);
					switchMode && (customSetting.switchMode = switchMode);
				}
				// 保存
				Ccay.Personalized.saveSetting(this.id, customSetting, function(){
					customSetting.showMessage!==false && Ccay.UI.topBox("ccay.common.message.success");
					/*
						*lwx wx200947 修复，个性保存时，下拉框值不能刷新。
						*op.hasColResize ? null : $.noop  改为回调，并手动获取igrid参数
					*/
					var curArr = JSON.parse(this.data)["settingKey"].split("#") ,
						curStr = curArr[ curArr.length - 1 ] ,
						igridOp = $("#"+curStr).data('op');
						
					if(igridOp.profileSelectPanel){
						var pageKey = Ccay.Personalized.getPageKey(),gridId=igridOp.id,settingKey=pageKey+"#"+gridId ,
							url = "services/ccay/personalized/setting/list/page?settingKey="+pageKey+"&gridId="+gridId;
						$(igridOp.profileSelectPanel).manager().reBind({url:url});
					}
				}, true);
			} else {
				// 恢复默认设置时，将个性化中的grid设置清除
				Ccay.Personalized.deleteSetting(this.id);
			}
		}
	});
})(Ccay.UI.IGrid);